package org.examples.java.io;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.io.StringReader;

import org.junit.After;
import org.junit.Test;

public class StringReaderTest {

    private static final String content = "Test string";

    StringReader reader = new StringReader(content);

    @After
    public void after() {
        reader.close();
    }

    @Test
    public void testRead() throws IOException {
        StringBuilder s = new StringBuilder();
        for (int c = reader.read(); c != -1; c = reader.read())
        {
            s.append(new Character((char) c));
        }
        assertEquals(content, s.toString());
    }

    @Test
    public void testReadCharArrayIntInt() throws IOException {
        char[] cbuf = new char[5];
        reader.read(cbuf, 0, 5);

        assertEquals(content.substring(0, 5), String.valueOf(cbuf));
    }

    @Test
    public void testSkip() throws IOException {
        assertEquals("T", String.valueOf((char) reader.read()));
        // skip ..es..
        reader.skip(2);
        assertEquals("t", String.valueOf((char) reader.read()));
    }

    @Test
    public void testReady() throws IOException {
        assertTrue(reader.ready());
        for (int c = reader.read(); c != -1; c = reader.read());
        // even after reaching the end the reader is ready
        assertTrue(reader.ready());
    }

    @Test(expected = IOException.class)
    public void testReadyFailed() throws IOException {
        reader.close();
        reader.ready();
    }

    @Test
    public void testMarkSupported() {
        assertTrue(reader.markSupported());
    }

    @Test
    public void testMarkReset() throws IOException {
        assertEquals("T", String.valueOf((char) reader.read()));

        reader.mark(0);
        assertEquals("e", String.valueOf((char) reader.read()));
        assertEquals("s", String.valueOf((char) reader.read()));

        // Back to "e"
        reader.reset();
        assertEquals("e", String.valueOf((char) reader.read()));
    }

    @Test(expected = IOException.class)
    public void testClose() throws IOException {
        reader.close();
        reader.read();
    }
}
